﻿using DocumentFormat.OpenXml.Lite.Core;
using DocumentFormat.OpenXml.Lite.Shared;
using DocumentFormat.OpenXml.Lite.Xml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace DocumentFormat.OpenXml.Lite.SpreadsheetML.Excel.StyleElements
{
    [XmlRoot("font", Namespace = Constants.ExcelMain)]
    public class Font : XmlSerializable
    {
        /// <summary>
        /// Hint: you cannot add two elements with the same type.
        /// </summary>
        [XmlElement("", Namespace = Constants.ExcelMain)]
        public XmlList<IFontStyleElement> Elements { get; set; }

        public Font()
        {
            Elements = new XmlList<IFontStyleElement>();
            Elements.Changing += StyleElements_Changing;
        }

        void StyleElements_Changing(object sender, ListEventArgs<IFontStyleElement> args)
        {
            if (args.Type == ListEventType.Remove)
                return;

            foreach (var obj in args.Objects)
            {
                if (obj.GetType() == typeof(IFontStyleElement))
                {
                    var element = Elements.FirstOrDefault(e => e.GetType() == obj.GetType());
                    if (obj != null)
                    {
                        throw new OpenXmlException("Element with the same type (" + 
                            element.GetType().ToString() + ") already added to list: " + Elements.ToString());
                    }
                }
            }
        }

        /// <summary>
        /// Hint: you cannot add two elements with the same type.
        /// </summary>
        /// <param name="element"></param>
        /// <returns>True, if the list not contains element with the same type. 
        /// False otherwise (in this case the content will be override the old one).</returns>
        public void AddElement(IFontStyleElement element)
        {
            var e = Elements.FirstOrDefault(s => s.GetType() == element.GetType());
            if (e != null)
            {
                e.Copy(element);
            }
            else
            {
                Elements.Add(element);
            }
        }
    }
}
